package com.kun.alldb.classloader;

import cn.hutool.core.io.FileUtil;

import java.net.URL;
import java.net.URLClassLoader;
import java.sql.Driver;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

/**
 * 自定义驱动类加载器
 *
 * @author kun.li
 */
public class DriverJarLoader extends URLClassLoader {
    /**
     * 驱动类缓存
     */
    private static final Map<String, Driver> driverCacheMap = new ConcurrentHashMap<>();
    /**
     * 类装入器交换器
     */
    private static final ClassLoaderSwapper classLoaderSwapper = ClassLoaderSwapper.newCurrentThreadClassLoaderSwapper();

    public DriverJarLoader(URL[] urls) {
        this(urls, DriverJarLoader.class.getClassLoader());
    }

    public DriverJarLoader(URL[] urls, ClassLoader parent) {
        super(urls, parent);
        for (URL url : urls) {
            String extName = FileUtil.extName(url.getFile());
            if (!extName.equalsIgnoreCase("jar")) {
                System.out.println("无法加载" + extName + "文件");
            }
        }
    }


    public static Driver loadDriver(String driverJar, String driverClassName) throws Exception {
        Driver driver = driverCacheMap.get(driverJar);
        if (driver != null) {
            return driver;
        }
        URL url = new URL(getWrapperDriverJarPath(driverJar));
        DriverJarLoader driverJarLoader = new DriverJarLoader(new URL[]{url});
        classLoaderSwapper.setCurrentThreadClassLoader(driverJarLoader);
        Class<?> clazz = driverJarLoader.loadClass(driverClassName);
        driver = (Driver) clazz.getDeclaredConstructor().newInstance();
        classLoaderSwapper.restoreCurrentThreadClassLoader();
        driverCacheMap.put(driverJar, driver);
        return driver;
    }

    private static String getWrapperDriverJarPath(String driverJar) {
        String platformName = System.getProperty("os.name");
        if (platformName.contains("Windows") && !driverJar.contains("file:")) {
            driverJar = "file:" + driverJar;
        }
        return driverJar;
    }
}
